import { mockRequestClient as defHttp } from '#/api/request';
import type { Resource } from './types';

enum Api {
  // 业态模板管理
  IndustryTemplate = '/resource/saas-factory/industry-template',

  // 资源组合管理
  ResourceCombo = '/resource/saas-factory/resource-combo',

  // SaaS应用构建
  BuildSaaS = '/resource/saas-factory/build',

  // 应用部署
  Deploy = '/resource/saas-factory/deploy',

  // 应用配置
  Config = '/resource/saas-factory/config',

  // 应用监控
  Monitor = '/resource/saas-factory/monitor',

  // 应用升级
  Upgrade = '/resource/saas-factory/upgrade',

  // 应用备份
  Backup = '/resource/saas-factory/backup',

  // 应用恢复
  Restore = '/resource/saas-factory/restore',

  // 应用市场
  Marketplace = '/resource/saas-factory/marketplace',
}

// 业态类型枚举
export enum IndustryType {
  HOTEL = 'hotel', // 酒店
  PET = 'pet', // 宠物
  EDUCATION = 'education', // 教育
  RETAIL = 'retail', // 零售
  MANUFACTURING = 'manufacturing', // 制造
  FINANCE = 'finance', // 金融
  HEALTHCARE = 'healthcare', // 医疗
  LOGISTICS = 'logistics', // 物流
  RESTAURANT = 'restaurant', // 餐饮
  FITNESS = 'fitness', // 健身
  BEAUTY = 'beauty', // 美容
  AUTOMOTIVE = 'automotive', // 汽车
}

// 业态模板
export interface IndustryTemplate {
  id: string;
  name: string;
  type: IndustryType;
  description: string;
  version: string;

  // 必需资源
  requiredResources: RequiredResource[];

  // 默认能力
  defaultCapabilities: DefaultCapability[];

  // 推荐配置
  recommendedConfig: RecommendedConfig;

  // 模板元数据
  metadata: {
    author: string;
    tags: string[];
    rating: number;
    downloads: number;
    lastUpdated: string;
    documentation?: string;
    examples?: string[];
  };
}

// 必需资源
export interface RequiredResource {
  resourceId: string;
  resourceType: string;
  resourceCategory: string;
  minQuantity: number;
  maxQuantity?: number;
  required: boolean;
  alternatives?: string[]; // 替代资源ID列表
}

// 默认能力
export interface DefaultCapability {
  capabilityId: string;
  capabilityType: string;
  config: any;
  enabled: boolean;
  priority: number;
}

// 推荐配置
export interface RecommendedConfig {
  pricing: {
    model: string;
    basePrice: number;
    currency: string;
  };
  features: {
    basic: string[];
    premium: string[];
    enterprise: string[];
  };
  integrations: string[];
  customizations: Array<{
    name: string;
    description: string;
    type: 'field' | 'workflow' | 'report';
    config: any;
  }>;
}

// 资源组合
export interface ResourceCombo {
  id: string;
  name: string;
  description: string;
  industryType: IndustryType;

  // 组合资源
  resources: ComboResource[];

  // 组合能力
  capabilities: ComboCapability[];

  // 组合配置
  config: ComboConfig;

  // 组合状态
  status: 'draft' | 'active' | 'deprecated';

  // 创建信息
  createdAt: string;
  updatedAt: string;
  createdBy: string;
}

// 组合资源
export interface ComboResource {
  resourceId: string;
  resourceType: string;
  resourceCategory: string;
  quantity: number;
  config?: any;
}

// 组合能力
export interface ComboCapability {
  capabilityId: string;
  capabilityType: string;
  config: any;
  enabled: boolean;
  dependencies: string[];
}

// 组合配置
export interface ComboConfig {
  pricing: {
    model: string;
    basePrice: number;
    currency: string;
    tiers?: Array<{
      name: string;
      price: number;
      features: string[];
    }>;
  };
  branding: {
    name: string;
    logo?: string;
    colors: {
      primary: string;
      secondary: string;
    };
  };
  features: {
    enabled: string[];
    disabled: string[];
    custom: Array<{
      name: string;
      config: any;
    }>;
  };
}

// SaaS应用
export interface SaaSApplication {
  id: string;
  name: string;
  description: string;
  industryType: IndustryType;

  // 应用配置
  config: SaaSConfig;

  // 应用状态
  status: 'building' | 'deploying' | 'running' | 'stopped' | 'error';

  // 部署信息
  deployment: {
    environment: 'dev' | 'staging' | 'prod';
    region: string;
    domain?: string;
    version: string;
    deployedAt?: string;
  };

  // 使用统计
  usage: {
    users: number;
    storage: number;
    bandwidth: number;
    lastActive: string;
  };

  // 创建信息
  createdAt: string;
  updatedAt: string;
  createdBy: string;
}

// SaaS配置
export interface SaaSConfig {
  // 基础配置
  basic: {
    name: string;
    description: string;
    version: string;
    language: string;
    timezone: string;
  };

  // 数据库配置
  database: {
    type: 'mysql' | 'postgresql' | 'mongodb';
    host: string;
    port: number;
    name: string;
    username: string;
    password: string;
  };

  // 存储配置
  storage: {
    type: 'local' | 's3' | 'oss';
    bucket?: string;
    region?: string;
    accessKey?: string;
    secretKey?: string;
  };

  // 邮件配置
  email: {
    provider: 'smtp' | 'sendgrid' | 'mailgun';
    host?: string;
    port?: number;
    username?: string;
    password?: string;
    apiKey?: string;
  };

  // 支付配置
  payment: {
    provider: 'stripe' | 'paypal' | 'alipay' | 'wechat';
    apiKey?: string;
    secretKey?: string;
    webhookUrl?: string;
  };
}

// 构建参数
export interface BuildSaaSParam {
  templateId: string;
  comboId?: string;
  config: {
    name: string;
    description: string;
    industryType: IndustryType;
    customizations?: Array<{
      name: string;
      config: any;
    }>;
  };
}

// 部署参数
export interface DeployParam {
  applicationId: string;
  environment: 'dev' | 'staging' | 'prod';
  region: string;
  config?: Partial<SaaSConfig>;
}

/**
 * SaaS工厂API
 */
export const SaaSFactoryApi = {
  /**
   * 获取业态模板列表
   */
  getIndustryTemplates: (params?: {
    type?: IndustryType;
    tags?: string[];
    rating?: number;
  }) =>
    defHttp.get<IndustryTemplate[]>({
      url: Api.IndustryTemplate,
      params,
    }),

  /**
   * 获取业态模板详情
   */
  getIndustryTemplate: (templateId: string) =>
    defHttp.get<IndustryTemplate>({
      url: `${Api.IndustryTemplate}/${templateId}`,
    }),

  /**
   * 创建业态模板
   */
  createIndustryTemplate: (params: Omit<IndustryTemplate, 'id' | 'metadata'>) =>
    defHttp.post<IndustryTemplate>({
      url: Api.IndustryTemplate,
      data: params,
    }),

  /**
   * 更新业态模板
   */
  updateIndustryTemplate: (
    templateId: string,
    params: Partial<IndustryTemplate>,
  ) =>
    defHttp.put<IndustryTemplate>({
      url: `${Api.IndustryTemplate}/${templateId}`,
      data: params,
    }),

  /**
   * 删除业态模板
   */
  deleteIndustryTemplate: (templateId: string) =>
    defHttp.delete<void>({
      url: `${Api.IndustryTemplate}/${templateId}`,
    }),

  /**
   * 获取资源组合列表
   */
  getResourceCombos: (params?: {
    industryType?: IndustryType;
    status?: string;
  }) =>
    defHttp.get<ResourceCombo[]>({
      url: Api.ResourceCombo,
      params,
    }),

  /**
   * 获取资源组合详情
   */
  getResourceCombo: (comboId: string) =>
    defHttp.get<ResourceCombo>({
      url: `${Api.ResourceCombo}/${comboId}`,
    }),

  /**
   * 创建资源组合
   */
  createResourceCombo: (
    params: Omit<ResourceCombo, 'id' | 'createdAt' | 'updatedAt' | 'createdBy'>,
  ) =>
    defHttp.post<ResourceCombo>({
      url: Api.ResourceCombo,
      data: params,
    }),

  /**
   * 更新资源组合
   */
  updateResourceCombo: (comboId: string, params: Partial<ResourceCombo>) =>
    defHttp.put<ResourceCombo>({
      url: `${Api.ResourceCombo}/${comboId}`,
      data: params,
    }),

  /**
   * 删除资源组合
   */
  deleteResourceCombo: (comboId: string) =>
    defHttp.delete<void>({
      url: `${Api.ResourceCombo}/${comboId}`,
    }),

  /**
   * 构建SaaS应用
   */
  buildSaaS: (params: BuildSaaSParam) =>
    defHttp.post<{
      applicationId: string;
      status: 'building';
      estimatedTime: number;
    }>({
      url: Api.BuildSaaS,
      data: params,
    }),

  /**
   * 获取SaaS应用列表
   */
  getSaaSApplications: (params?: {
    industryType?: IndustryType;
    status?: string;
    createdBy?: string;
  }) =>
    defHttp.get<SaaSApplication[]>({
      url: Api.BuildSaaS,
      params,
    }),

  /**
   * 获取SaaS应用详情
   */
  getSaaSApplication: (applicationId: string) =>
    defHttp.get<SaaSApplication>({
      url: `${Api.BuildSaaS}/${applicationId}`,
    }),

  /**
   * 部署SaaS应用
   */
  deploySaaS: (params: DeployParam) =>
    defHttp.post<{
      deploymentId: string;
      status: 'deploying';
      estimatedTime: number;
    }>({
      url: Api.Deploy,
      data: params,
    }),

  /**
   * 获取部署状态
   */
  getDeploymentStatus: (deploymentId: string) =>
    defHttp.get<{
      status: 'deploying' | 'success' | 'failed';
      progress: number;
      logs: string[];
      error?: string;
    }>({
      url: `${Api.Deploy}/${deploymentId}`,
    }),

  /**
   * 配置SaaS应用
   */
  configSaaS: (applicationId: string, config: Partial<SaaSConfig>) =>
    defHttp.put<{
      success: boolean;
      message: string;
    }>({
      url: `${Api.Config}/${applicationId}`,
      data: config,
    }),

  /**
   * 获取SaaS应用监控数据
   */
  getSaaSMetrics: (applicationId: string, timeRange: string) =>
    defHttp.get<{
      cpu: Array<{ timestamp: string; value: number }>;
      memory: Array<{ timestamp: string; value: number }>;
      disk: Array<{ timestamp: string; value: number }>;
      network: Array<{ timestamp: string; value: number }>;
      requests: Array<{ timestamp: string; value: number }>;
      errors: Array<{ timestamp: string; value: number }>;
    }>({
      url: `${Api.Monitor}/${applicationId}`,
      params: { timeRange },
    }),

  /**
   * 升级SaaS应用
   */
  upgradeSaaS: (applicationId: string, version: string) =>
    defHttp.post<{
      upgradeId: string;
      status: 'upgrading';
      estimatedTime: number;
    }>({
      url: `${Api.Upgrade}/${applicationId}`,
      data: { version },
    }),

  /**
   * 备份SaaS应用
   */
  backupSaaS: (applicationId: string, description?: string) =>
    defHttp.post<{
      backupId: string;
      status: 'backing_up';
      estimatedTime: number;
    }>({
      url: `${Api.Backup}/${applicationId}`,
      data: { description },
    }),

  /**
   * 恢复SaaS应用
   */
  restoreSaaS: (applicationId: string, backupId: string) =>
    defHttp.post<{
      restoreId: string;
      status: 'restoring';
      estimatedTime: number;
    }>({
      url: `${Api.Restore}/${applicationId}`,
      data: { backupId },
    }),

  /**
   * 获取SaaS应用市场
   */
  getSaaSMarketplace: (params?: {
    industryType?: IndustryType;
    priceRange?: string;
    rating?: number;
    sortBy?: 'popularity' | 'rating' | 'price' | 'date';
    sortOrder?: 'asc' | 'desc';
  }) =>
    defHttp.get<{
      applications: SaaSApplication[];
      total: number;
      facets: {
        industryTypes: Record<IndustryType, number>;
        priceRanges: Record<string, number>;
        ratings: Record<string, number>;
      };
    }>({
      url: Api.Marketplace,
      params,
    }),
};
